
//
//  NSString+Common.m
//  ArtDog
//
//  Created by dllo on 16/8/29.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NSString+Encryption.h"
#import <CommonCrypto/CommonCrypto.h>
#import "HLMacro.h"

@implementation NSString (Encryption)


#pragma mark - 加密
- (NSString *)stringWithMD5
{
    const char *cString = [self UTF8String];
    CC_LONG length = (CC_LONG)strlen(cString);
    unsigned char bytes[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cString, length, bytes);
    // 将c字符串转换成oc字符串
    NSMutableString *string = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [string appendFormat:@"%02x", bytes[i]];
    }
    return string;
}

- (NSString *)stringWith32BitMD5Upper
{
    return [[self stringWithMD5]uppercaseString];
}

- (NSString *)stringWith32BitMD5Lower
{
    return [[self stringWithMD5]lowercaseString];
}

- (NSString *)stringWith16BitMD5Upper
{
    NSRange range = NSMakeRange(8, 16);
    return [[[self stringWithMD5]substringWithRange:range]uppercaseString];
}

- (NSString *)stringWith16BitMD5Lower
{
    NSRange range = NSMakeRange(8, 16);
    return [[[self stringWithMD5]substringWithRange:range]lowercaseString];
}


#pragma mark -SHA_1
- (NSString *)stringWithSHA_1
{
    const char *cString = [self UTF8String];
    CC_LONG len = (CC_LONG)strlen(cString);
    unsigned char bytes[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(cString, len, bytes);
    NSMutableString *string = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH];
    for (int i = 0; i< CC_SHA1_DIGEST_LENGTH; i++) {
        [string appendFormat:@"%02x", bytes[i]];
    }
    return string;
}

#pragma mark - Base64
/**
 * 1.Base64 编码格式 一般应用于少量数据的编码
 *
 **/

/** 编码 */
- (NSString *)stringWithBase64
{
    NSData *stringData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [stringData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    return base64String;
}

- (NSString *)base64WithString
{
    NSData *base64Data = [[NSData alloc]initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *orginString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    return orginString;
}

@end
